//引入express
const express = require('express')
//引入body接参
const bodyParser = require('body-parser')
//引入cooke管理
const cookieParser = require('cookie-parser')
//引入路由
const userRouter = require('./user')
const model = require('./model')
const Chat = model.getModel('chat')
const app = express()
// 获取项目绝对路径
const path = require("path")
// 引入并设置socket.io
const server = require("http").Server(app)
const io = require('socket.io')(server)
app.use(cookieParser())
app.use(bodyParser.json())
app.use('/user', userRouter)
// app.listen(9093, function () {
// 	console.log('Node app start at port 9093')
// })
//请求处理
app.use(function(req,res,next){
	if(req.url.startsWith("/user/") || req.url.startsWith("/static/")){
		return next();
	}
	//修正路径
	return res.sendFile(path.resolve('build/index.html'));
})

//请求拦截引向build目录
app.use('/',express.static(path.resolve('build')));
io.on("connection", socket => {
	socket.on("sendmsg", data => {  // 监听的频道必须和客户端监听的频道相同，等待消息
		const {msg,from,to} = data;

		const chatid = [from,to].sort().join("_");
		Chat.create({from,to,chatid,content:msg},(err,doc)=>{
			console.log("收到用户发来的消息");
			io.emit("recvmsg", Object.assign({},doc._doc));  // 向所有客户端发送信息
		})
    });
	//链接失败
	socket.on('disconnect', () => {
		console.log("socket is disconnect");
	})
	//全局发生广播
	// io.emit('broadcasting', () => {
	// 	// 全部进行广播，发送消息
	// })
})


server.listen(9093, () => {
	console.log("socket is listen in 9093");
})


